<template>
  <div class="wrapper">
    <ul class="alphabet-list">
      <li
        class="alphabet-item"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchEnd="handleTouchEnd"
        @click="handleLetterClick"
      >
      {{item}}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: {
      type: Object
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  computed: {
    letters () {
      const letters = []
      for (let key in this.cities) {
        letters.push(key)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      const text = e.target.innerText
      this.$emit('change', text)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const MoveY = e.touches[0].clientY - 80
          const index = Math.floor((MoveY - this.startY) / 22)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
          this.timer = null
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variable.styl'
  .wrapper
    position  fixed
    top 160px
    right 0
    height 100%
    display flex
    .alphabet-list
      margin-top 90px
      .alphabet-item
        font-size 20px
        width 40px
        text-align center
        line-height 44px
        color $bgColor
</style>
